package com.easyapi.job;

import com.alibaba.druid.pool.DruidDataSource;
import com.easyapi.common.bean.ApiCenterDatasource;
import com.easyapi.common.emun.DataSourceStatus;
import com.easyapi.common.emun.SqlDriverClassName;
import com.easyapi.config.PoolConfig;
import com.easyapi.mapper.ApiCenterDatasourceMapper;
import com.easyapi.utils.CaffeineCacheUtil;
import com.easyapi.utils.DruidDataSourceUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;

/**
 * @author javadadi
 */
@Component
@Slf4j
public class DatasourceJob {
    @Resource
    private ApiCenterDatasourceMapper datasourceMapper;

    private Boolean initDruidDatasource() {
        PoolConfig.RUN_SYNC_JOB_POOL.submit(() -> {
            log.info("update datasource start{}",System.currentTimeMillis());
            List<ApiCenterDatasource> datasourceList = datasourceMapper.listAllDatasource();
            for (ApiCenterDatasource apiCenterDatasource : datasourceList) {
                Long id = apiCenterDatasource.getId();
                String dataName = apiCenterDatasource.getDataName();
                String dataDesc = apiCenterDatasource.getDataDesc();
                String datasourceUsername = apiCenterDatasource.getDatasourceUsername();
                String datasourcePassword = apiCenterDatasource.getDatasourcePassword();
                String dataJson = apiCenterDatasource.getDataJson();
                DruidDataSource druidDataSource = DruidDataSourceUtil.getDruidDataSource(dataJson, datasourceUsername, datasourcePassword, SqlDriverClassName.MYSQL.getDriverClassName());
                if (Objects.isNull(druidDataSource)) {
                    //初始化失败就更新一下链接状态
                    apiCenterDatasource.setLinkState(DataSourceStatus.LINK_FAIL.getCode());
                    log.error("datasource init error ，datasourceId:{},datasourceName:{},datasourceDesc:{}", id, dataName, dataDesc);
                    continue;
                }
                CaffeineCacheUtil.add(dataName + "_" + id, druidDataSource);
            }
            if (CollectionUtils.isNotEmpty(datasourceList)) {
                datasourceList.forEach(datasource -> {
                    datasourceMapper.updateById(datasource);
                });
            }
            log.info("update datasource end{}",System.currentTimeMillis());
        });
        return true;
    }

    @PostConstruct
    @Scheduled(cron = "0 23 12 */3 * ?")
    public void initDatasource(){
        initDruidDatasource();
    }
}
